package com.javabasic.algorithm.leetcode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * n叉树的程序遍历
 */
public class N_aryTreeLevelOrderTraversal {
    public List<List<Integer>> levelOrder(Node root) {

        List<List<Integer>> result = new ArrayList<>();
        if (root == null) return result;
        executorLevelOrder(root,result);
        return result;
    }
    public void executorLevelOrder(Node root,List<List<Integer>> result) {
        LinkedList<Node> queue1 = new LinkedList<>();
        LinkedList<Node> queue2 = new LinkedList<>();
        queue1.add(root);
        while (!queue1.isEmpty()) {
            ArrayList<Integer> integers1 = new ArrayList<>();
            while (queue1.isEmpty() == false) {
                Node cur = queue1.getFirst();
                queue1.removeFirst();
                integers1.add(cur.val);
                int len = cur.children.size();
                for (int i = 0; i < len; i++) {
                    queue2.add(cur.children.get(i));
                }
            }
            result.add(integers1);
            if (queue2.isEmpty() == false) {
                ArrayList<Integer> integers2 = new ArrayList<>();
                while (queue2.isEmpty() == false) {
                    Node cur = queue2.getFirst();
                    queue2.removeFirst();
                    integers2.add(cur.val);
                    int len = cur.children.size();
                    for (int i = 0; i < len; i++) {
                        queue1.add(cur.children.get(i));
                    }
                }
                result.add(integers2);
            }

        }

    }
}
/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val,List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/